package com.example.yichuangyun.mvvm.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.FragmentCallDetailsAnalysisBinding;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.mvvm.base.BaseFragment;
import com.example.yichuangyun.mvvm.ui.activity.CallRecordActivity;
import com.example.yichuangyun.mvvm.ui.fragment.view.CallDetailsTextViewModel;
import com.example.yichuangyun.utils.ToastHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon;
import io.noties.markwon.core.MarkwonTheme;

/**
 * 通话详情沟通记录--语义诉求分析
 */
public class CallDetailsAnalysisFragment extends BaseFragment<FragmentCallDetailsAnalysisBinding, CallDetailsTextViewModel> {

    private static final int MAX_REQUESTS = 20;
    private int requestCount = 0;
    private Handler handler;
    /**
     * 音频地址
     */
    private String url, id;
    /**
     * 音频总时长
     */
    private long duration;
    /**
     * 是否进行语音转文字，是否分析
     */
    private boolean isTransText, isAnalysis;
    private Markwon markwon;

    public static CallDetailsAnalysisFragment newInstance(String id, String url, long duration) {
        Bundle bundle = new Bundle();
        bundle.putString(Constant.idKey, id);
        bundle.putString(Constant.urlKey, url);
        bundle.putLong(Constant.durationKey, duration);
        CallDetailsAnalysisFragment fragment = new CallDetailsAnalysisFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected CallDetailsTextViewModel bindModel() {
        return getViewModel(this, CallDetailsTextViewModel.class);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initData() {
        handler = new Handler();
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        markwon = Markwon.builder(mContext).usePlugin(new AbstractMarkwonPlugin() {
            @Override
            public void configureTheme(@NonNull MarkwonTheme.Builder builder) {
                builder.thematicBreakColor(ContextCompat.getColor(mContext, R.color.color_E7E7E7)).thematicBreakHeight(2) //设置水平线颜色和高度
                        .headingTextSizeMultipliers(new float[]{1.1f, 1.1f, 1.1f, 1.1f, 1.1f, 1f}); //设置各级标题的文本大小比例
            }
        }).build();
        if (bundle != null) {
            id = bundle.getString(Constant.idKey);
            url = bundle.getString(Constant.urlKey);
            duration = bundle.getLong(Constant.durationKey);
        }
    }

    @Override
    protected void initClick() {
        viewModel.transTextSuccess.observe(this, callRecordTransModel -> {
            if (!TextUtils.isEmpty(callRecordTransModel.getAnalyseResult())) {
                String result = callRecordTransModel.getAnalyseResult();
                markwon.setMarkdown(binding.contentTv, result);
                binding.transLl.setVisibility(View.GONE);
                binding.refreshLl.setVisibility(View.VISIBLE);
            } else {
                changeStatus(R.drawable.shape_1ae55c5c_50dp_bg, R.mipmap.icon_exe,
                        mContext.getString(R.string.file_exception), R.color.color_E55C5C, false);
            }
        });

        viewModel.mErrorData.observe(this, s -> {
            // 无法识别
            changeStatus(R.drawable.shape_1ae55c5c_50dp_bg, R.mipmap.icon_exe,
                    mContext.getString(R.string.file_exception), R.color.color_E55C5C, false);
        });

        viewModel.requestAgain.observe(this, s -> {
            if (requestCount < MAX_REQUESTS) {
                requestCount++;
                // res?.msg === '该录音正在转换中，请等待处理完成！'  这个是正在转化中  要循环请求 直到转化完成
                // 延迟 10 秒后再次进行网络请求，20次后停止
                handler.postDelayed(this::getTranscription, 10000);
            } else {
                // 无法识别
                changeStatus(R.drawable.shape_1ae55c5c_50dp_bg, R.mipmap.icon_exe,
                        mContext.getString(R.string.file_exception), R.color.color_E55C5C, false);
            }
        });

        //语音分析
        viewModel.onDelayClick(binding.transLl, o -> {
            if (binding.transTv.getText().toString().equals(getString(R.string.click_voice_analysis))) {
                if (isTransText) {
                    if (duration > 60) {
                        // 点击语音分析
                        changeStatus(R.drawable.shape_fff4f7ff_50dp_bg, R.mipmap.icon_ai_sel,
                                mContext.getString(R.string.click_voice_analysis), R.color.color_4371FF, false);
                        getTranscription();
                    } else {
                        ToastHelper.show(mContext.getString(R.string.cannot_generate_analysis));
                    }
                } else {
                    ToastHelper.show(mContext.getString(R.string.trans_text_generate_analysis));
                }
            }
        });

        //重新分析
        viewModel.onDelayClick(binding.againLl, o -> getTranscription());
    }

    private void getTranscription() {
        if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(url)) {
            // 分析中
            changeStatus(R.drawable.shape_4371ff_50dp_bg, R.mipmap.loading,
                    mContext.getString(R.string.identifying_call_content), R.color.white, true);
            //  type -1 第一次拉取   0 沟通内容   1 智能需求分析   2 沟通内容重新生成（已经废弃 不重复生成）
            viewModel.getTranscription(id, url, 1, null);
        }
    }

    private void changeStatus(int backgroundResource, int imageResource, String text, int color, boolean isLoading) {
        binding.transLl.setBackgroundResource(backgroundResource);
        if (isLoading) {
            // 加载本地GIF
            Glide.with(this)
                    .asGif()
                    .load(imageResource)
                    .into(binding.transIv);
        } else {
            binding.transIv.setImageResource(imageResource);
        }
        binding.transTv.setText(text);
        binding.transTv.setTextColor(ContextCompat.getColor(mContext, color));
        binding.transLl.setVisibility(View.VISIBLE);
        binding.contentTv.setText("");
        binding.refreshLl.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getStatus() == 100) {
                isAnalysis = true;
                String result = eventBusModel.getMsg();
                markwon.setMarkdown(binding.contentTv, result);
                binding.transLl.setVisibility(View.GONE);
                binding.refreshLl.setVisibility(View.VISIBLE);
            } else {
                if (eventBusModel.getMsg().equals(Constant.ALREADY_TRANS_TEXT)) {
                    isTransText = true;
                    if (duration > 60 && !isAnalysis) {
                        // 点击语音分析
                        changeStatus(R.drawable.shape_fff4f7ff_50dp_bg, R.mipmap.icon_ai_sel,
                                mContext.getString(R.string.click_voice_analysis), R.color.color_4371FF, false);
                    }
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 移除所有未执行的任务，避免内存泄漏
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
